package com.yonyou.cyxdms.basedata.service.service.series;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yonyou.cloud.http.plus.remote.IRemoteInvoke;
import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.framework.service.excel.*;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.bean.dto.ImportResultDto;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.bean.BeanMapperUtil;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.basedata.client.constants.BaseDataCommonConstants;
import com.yonyou.cyxdms.basedata.client.constants.BaseDataDictConstants;
import com.yonyou.cyxdms.basedata.client.domains.vo.BrandCacheVO;
import com.yonyou.cyxdms.basedata.client.domains.vo.MQBaseVO;
import com.yonyou.cyxdms.basedata.client.domains.vo.SeriesCacheVO;
import com.yonyou.cyxdms.basedata.service.constant.BasedataCommonConstants;
import com.yonyou.cyxdms.basedata.service.constant.BasedataDictConstants;
import com.yonyou.cyxdms.basedata.service.constant.CommonConstant;
import com.yonyou.cyxdms.basedata.service.dto.vehiclemodel.GeneralSeriesDTO;
import com.yonyou.cyxdms.basedata.service.dto.vehiclemodel.SeriesImportDTO;
import com.yonyou.cyxdms.basedata.service.dto.vehiclemodel.SeriesModifyDTO;
import com.yonyou.cyxdms.basedata.service.dto.vehiclemodel.SeriesQueryDTO;
import com.yonyou.cyxdms.basedata.service.entity.brand.BrandPO;
import com.yonyou.cyxdms.basedata.service.entity.series.SeriesPO;
import com.yonyou.cyxdms.basedata.service.repository.basedata.SystemParamMapper;
import com.yonyou.cyxdms.basedata.service.repository.brand.BrandMapper;
import com.yonyou.cyxdms.basedata.service.repository.series.SeriesMapper;
import com.yonyou.cyxdms.basedata.service.service.brand.BrandService;
import com.yonyou.cyxdms.basedata.service.util.MQUtils;
import com.yonyou.cyxdms.basedata.service.util.MapUtils;
import com.yonyou.cyxdms.basedata.service.vo.CarparamVO;
import com.yonyou.cyxdms.basedata.service.vo.CarserialDetailsVO;
import com.yonyou.cyxdms.basedata.service.vo.CarserialInfoVO;
import com.yonyou.cyxdms.basedata.service.vo.series.SeriesDictVO;
import com.yonyou.cyxdms.basedata.service.vo.series.VehicleProductSeriesVO;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysmanage.client.service.login.DealerBrandService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 车系
 *
 * @author renwd
 * @since 2018/12/10
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class SeriesServiceImpl implements SeriesService {

    public static final Logger logger = LoggerFactory.getLogger(SeriesServiceImpl.class);

    @Autowired
    private BrandService brandService;

    @Autowired
    private SeriesMapper seriesMapper;

    @Autowired
    private ExcelGenerator excelService;

    @Autowired
    private ExcelRead<SeriesImportDTO> excelSeriesService;

    @Autowired
    DealerBrandService dealerBrandService;

    @Autowired
    CarserialService carserialService;

    @Autowired
    SystemParamMapper systemParamMapper;

    @Autowired
    IRemoteInvoke iRemoteInvoke;

    @Autowired
    private RedisClient redisClient;
    @Autowired
    BrandMapper brandMapper;

    /**
     * 按条件查询车系信息
     *
     * @param queryParam
     * @return java.util.List<com.yonyou.cyxdms.basedata.client.domains.DTO.basedata.SeriesCacheVO>
     * @author renwd
     * @since 2018/12/10
     */
    @Override
    @Transactional(readOnly = true)
    public List<SeriesCacheVO> querySeriesByCondition(Map<String, Object> queryParam) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        //获取所有品牌
        List<BrandPO> brandPos = brandMapper.selectList(new LambdaQueryWrapper<BrandPO>().eq(BrandPO::getAppId, CommonConstant.APP_ID_RL));
        List<Long> brandIdList = brandPos.stream().map(t -> t.getBrandId()).collect(Collectors.toList());
        queryParam.put(BasedataCommonConstants.DEALER_BRNAND_LIST, brandIdList);

        queryParam.put("appId", CommonConstant.APP_ID_RL);
        return seriesMapper.querySeriesByCondition(queryParam);
    }

    /**
     * 根据品牌Id查询车系信息
     *
     * @param brandId
     * @return java.util.List<com.yonyou.cyxdms.basedata.client.domains.DTO.basedata.SeriesCacheVO>
     * @author guorp
     * @since 2018/12/13
     */
    @Override
    public List<SeriesCacheVO> getSeriesByBrandId(Long brandId) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return seriesMapper.getSeriesByBrandId(brandId, loginInfo.getGroupCode(), loginInfo.getAppId());
    }

    /**
     * @description：据车系名称模糊查询
     * @author ：quankk
     * @date ：Created in 2019/1/15 11:09
     * @modified By：
     */
    @Override
    public List<SeriesCacheVO> seriesBySeriesName(String appId, String seriesName) {
        return seriesMapper.seriesBySeriesName(appId, seriesName);
    }

    /**
     * @description：查询所有车系
     * @author ：quankk
     * @date ：Created in 2019/1/15 15:23
     * @modified By：
     */
    @Override
    public List<SeriesCacheVO> allSeries() {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String dealerCode = loginInfo.getOwnerCode();
        return seriesMapper.allSeries(dealerCode, loginInfo.getAppId());
    }

    /**
     * 根据品牌ID查询车系列表信息
     *
     * @author dengqiang
     * @since 2019/1/2
     */
    @Override
    public List<CarserialInfoVO> queryCarserialInfo(String brandId) {
        String appId = ApplicationContextHelper.getBeanByType(LoginInfoDto.class).getAppId();
        //根据品牌id获取车系
        LambdaQueryWrapper<SeriesPO> queryWrapper = new QueryWrapper<SeriesPO>().lambda();
        if (!StringUtils.isNullOrEmpty(brandId)) {
            queryWrapper.eq(SeriesPO::getBrandId, brandId);
        }
        queryWrapper.eq(SeriesPO::getAppId, appId);
        List<SeriesPO> carserialList = seriesMapper.selectList(queryWrapper);

        //返回车系信息（车系id,车系名称）
        List<CarserialInfoVO> carSerialInfoVos = new ArrayList<>();
        for (SeriesPO carserial : carserialList) {
            CarserialInfoVO carserialInfoVO = new CarserialInfoVO();
            carserialInfoVO.setCarserialId(carserial.getSeriesId());
            carserialInfoVO.setName(carserial.getSeriesName());
            carserialInfoVO.setMinPrice(carserial.getMinPrice());
            carserialInfoVO.setMaxPrice(carserial.getMaxPrice());
            carserialInfoVO.setCarserialPic(carserial.getCarserialPic());
            carserialInfoVO.setShareUrl(carserial.getShareUrl());
            carserialInfoVO.setTodetailUrl(carserial.getTodetailUrl());
            carserialInfoVO.setIntroduction(carserial.getIntroduction());
            carSerialInfoVos.add(carserialInfoVO);
        }


        return carSerialInfoVos;
    }


    /**
     * 根据车系ID查询车系详情
     *
     * @author dengqiang
     * @since 2019/1/2
     */
    @Override
    public CarserialDetailsVO queryCarserialDetails(Long carserialId) {
        String appId = ApplicationContextHelper.getBeanByType(LoginInfoDto.class).getAppId();
        //根据车系id获取车系
        LambdaQueryWrapper<SeriesPO> queryWrapper = new QueryWrapper<SeriesPO>().lambda();
        queryWrapper.eq(SeriesPO::getSeriesId, carserialId);
        queryWrapper.eq(SeriesPO::getAppId, appId);
        SeriesPO carserial = seriesMapper.selectOne(queryWrapper);
        //创建车系详情对象
        CarserialDetailsVO carserialDetailsVO = new CarserialDetailsVO();
        //设置车系基本信息
        carserialDetailsVO.setCarserialId(carserial.getSeriesId());
        carserialDetailsVO.setName(carserial.getSeriesName());
        //根据车系ID获取车型信息列表
        List<CarparamVO> carParamVos = null;
        //根据车系ID获取所有车型ID列表
        carserialService.doCarserialDetails(carParamVos, carserialDetailsVO);
        return carserialDetailsVO;
    }

    /**
     * 查询车系信息（pc）
     *
     * @param page
     * @param seriesQueryDTO
     * @author Tansj
     * @since 2019/11/15
     */
    @Transactional(readOnly = true)
    @Override
    public IPage<VehicleProductSeriesVO> queryVehicleProductSeries(Page page, SeriesQueryDTO seriesQueryDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = seriesQueryDTO.toMaps();
        queryParam = brandService.setLoginInfoParam(queryParam, loginInfoDto);
        logger.info("查询车系IPage的queryParam:---------{}", queryParam);
        /**
         * 车系数据放置redis
         */
        String appId = loginInfoDto.getAppId();
        String  messageFormat = MessageFormat.format(BasedataCommonConstants.SERIAL_CACHE_PRODUCT_SERIESID, appId);
        Object seriesData = redisClient.get(messageFormat);
        if (null == seriesData) {
            LambdaQueryWrapper<SeriesPO> seriesParam = new QueryWrapper<SeriesPO>().lambda();
            seriesParam.eq(SeriesPO::getAppId, appId).orderByAsc(SeriesPO::getPowerType,SeriesPO::getSeriesCode);
            List<SeriesPO> seriesList = seriesMapper.selectList(seriesParam);
            List<SeriesCacheVO> seriesVOList = BeanMapperUtil.copyList(seriesList, SeriesCacheVO.class);
            redisClient.set(messageFormat, JSONUtil.objectToJson(seriesVOList), BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
        }
        page.setRecords(seriesMapper.queryVehicleProductSeriesPage(page, queryParam));
        return page;
    }

    /**
     * dcs查询车系信息
     *
     * @param page
     * @param queryParam
     * @return java.util.List<com.yonyou.cyxdms.basedata.service.vo.brand.VehicleProductDcsBrandVO>
     * @author renwd
     * @since 2019/7/18
     */
    @Override
    public IPage<VehicleProductSeriesVO> queryDcsVehicleProductBrand(Page page, Map<String, Object> queryParam) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        MapUtils.addParameter(queryParam, loginInfoDto.getOwnerCode(), loginInfoDto.getAppId(), loginInfoDto.getGroupCode());
        queryParam.put(BasedataCommonConstants.ORG_TYPE, loginInfoDto.getOrgType());
        page.setRecords(seriesMapper.queryVehicleProductDcsSeries(page, queryParam));
        return page;
    }

    /**
     * 新增车系
     *
     * @param seriesDTO
     * @return java.lang.Integer
     * @author renwd
     * @since 2019/7/11
     */
    @Override
    public Integer addSeries(SeriesModifyDTO seriesDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        QueryWrapper<SeriesPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(SeriesPO::getAppId, loginInfoDto.getAppId())
                .in(SeriesPO::getOwnerCode, loginInfoDto.getOwnerCode())
                .and(obj ->
                        obj.eq(SeriesPO::getSeriesCode, seriesDTO.getSeriesCode())
                                .or()
                                .eq(SeriesPO::getSeriesName, seriesDTO.getSeriesName()));
        // 判断同一家店面中是否存在相同的车系代码或名称
        List<SeriesPO> seriesPos = seriesMapper.selectList(queryWrapper);
        if (!CommonUtils.isNullOrEmpty(seriesPos)) {
            throw new ServiceBizException(BasedataCommonConstants.SERIES_NOT_REPEAT);
        }
        SeriesPO seriesPo = BeanMapperUtil.copyProperties(seriesDTO, SeriesPO.class);
        Integer insertSize = seriesMapper.insert(seriesPo);
        // 车系消息发送到MQ
        sendSeries(seriesPo, BasedataCommonConstants.BIZ_SERIES_INSERT);
        // 删除redis缓存
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.SERIAL_CACHE_SERIES_ALL, loginInfoDto.getAppId(), loginInfoDto.getOwnerCode());
        redisClient.del(messageFormat);

        return insertSize;
    }

    /**
     * dcs新增车系
     *
     * @param seriesDTO
     * @return java.lang.Integer
     * @author renwd
     * @since 2019/7/11
     */
    @Override
    public Integer addDcsSeries(SeriesModifyDTO seriesDTO) {
        String appId = BasedataCommonConstants.APP_ID_RL;
        String groupCode = "-1";
        QueryWrapper<SeriesPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(SeriesPO::getAppId, appId)
                .and(obj ->
                        obj.eq(SeriesPO::getSeriesCode, seriesDTO.getSeriesCode()));
        // 判断同一家店面中是否存在相同的车系代码或名称
        List<SeriesPO> seriesPos = seriesMapper.selectList(queryWrapper);
        if (!CommonUtils.isNullOrEmpty(seriesPos)) {
            return 0;
        }
        SeriesPO seriesPo = BeanMapperUtil.copyProperties(seriesDTO, SeriesPO.class);
        seriesPo.setDataSources(BasedataDictConstants.DATA_SOURCES_BY_SUPER);
        seriesPo.setAppId(BasedataCommonConstants.APP_ID_RL);
        seriesPo.setCompanyCode("-1");
        seriesPo.setOwnerCode("-1");
        seriesPo.setOwnerParCode("-1");
        seriesPo.setIsIssue(BasedataDictConstants.IS_NO_SEND);
        Integer insertSize = seriesMapper.insert(seriesPo);
        // 删除redis缓存
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.SERIAL_CACHE_SERIES_ALL, appId, groupCode);
        redisClient.del(messageFormat);
        String productFormat = MessageFormat.format(BaseDataCommonConstants.PRODUCT_CACHE_DATA, appId, BasedataCommonConstants.PRODUCT_REDIS_TYPE, BasedataCommonConstants.PRODUCT_REDIS_LEVEL);
        redisClient.del(productFormat);
        return insertSize;
    }

    /**
     * 车系信息发送到MQ
     *
     * @param seriesPo
     * @author ysj
     * @date 2019/10/23
     */
    public void sendSeries(SeriesPO seriesPo, String bizId) {
        List<SeriesPO> seriesList = new ArrayList<>();
        seriesList.add(seriesPo);
        MQBaseVO<List<SeriesPO>> seriesMq = new MQBaseVO<>(seriesList, seriesPo.getAppId(), seriesPo.getOwnerCode());
        MQUtils.sendMsg(seriesMq.toMap(), bizId, systemParamMapper, iRemoteInvoke);
    }

    /**
     * 修改车系
     *
     * @param id
     * @param seriesDTO
     * @return java.lang.Integer
     * @author Tansj
     * @since 2019/11/15
     */
    @Override
    public Integer modifySeries(Long id, SeriesModifyDTO seriesDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        SeriesPO seriesPo = seriesMapper.selectById(id);
        if (seriesPo != null) {
            QueryWrapper<SeriesPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .in(SeriesPO::getOwnerCode, loginInfoDto.getOwnerCode())
                    .eq(SeriesPO::getAppId, loginInfoDto.getAppId())
                    .notIn(SeriesPO::getSeriesId, id)
                    .and(obj ->
                            obj.eq(SeriesPO::getSeriesCode, seriesDTO.getSeriesCode())
                                    .or()
                                    .eq(SeriesPO::getSeriesName, seriesDTO.getSeriesName()));
            // 判断同一家店面中是否存在相同的车系代码或名称
            List<SeriesPO> seriesPos = seriesMapper.selectList(queryWrapper);
            if (!CommonUtils.isNullOrEmpty(seriesPos)) {
                throw new ServiceBizException(BasedataCommonConstants.SERIES_NOT_REPEAT);
            } else {
                seriesPo.setBrandId(seriesDTO.getBrandId());
                seriesPo.setRecordVersion(seriesDTO.getRecordVersion());
                seriesPo.setSeriesCode(seriesDTO.getSeriesCode());
                seriesPo.setSeriesName(seriesDTO.getSeriesName());
                seriesPo.setDataSources(seriesDTO.getDataSources());
                seriesPo.setIsValid(seriesDTO.getIsValid());
                seriesPo.setStartDate(seriesDTO.getStartDate());
                seriesPo.setPowerType(seriesDTO.getPowerType());
                seriesPo.setUpdatedAt(LocalDateTime.now());
                int updateSize = seriesMapper.updateById(seriesPo);
                if (updateSize == 0) {
                    throw new ServiceBizException(BasedataCommonConstants.UPDATE_FAILED);
                }
                // 发送车系消息到MQ
                sendSeries(seriesPo, BasedataCommonConstants.BIZ_SERIES_UPDATE);
                // 删除redis缓存
                String messageFormat = MessageFormat.format(BaseDataCommonConstants.SERIAL_CACHE_SERIES_ALL, loginInfoDto.getAppId(), loginInfoDto.getOwnerCode());
                redisClient.del(messageFormat);
                return updateSize;
            }
        } else {
            throw new ServiceBizException("后台不存在该车系！");
        }
    }

    /**
     * dcs修改车系
     *
     * @param id
     * @param seriesDTO
     * @return java.lang.Integer
     * @author Tansj
     * @since 2019/11/15
     */
    @Override
    public Integer modifyDcsSeries(Long id, SeriesModifyDTO seriesDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        SeriesPO seriesPo = seriesMapper.selectById(id);
        if (seriesPo != null) {
            QueryWrapper<SeriesPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .in(SeriesPO::getOwnerCode, loginInfoDto.getGroupCode(), "-1")
                    .eq(SeriesPO::getAppId, loginInfoDto.getAppId())
                    .notIn(SeriesPO::getSeriesId, id)
                    .and(obj ->
                            obj.eq(SeriesPO::getSeriesCode, seriesDTO.getSeriesCode())
                                    .or()
                                    .eq(SeriesPO::getSeriesName, seriesDTO.getSeriesName()));
            // 判断同一家店面中是否存在相同的车系代码或名称
            List<SeriesPO> seriesPos = seriesMapper.selectList(queryWrapper);
            if (!CommonUtils.isNullOrEmpty(seriesPos)) {
                throw new ServiceBizException(BasedataCommonConstants.SERIES_NOT_REPEAT);
            } else {
                seriesPo.setBrandId(seriesDTO.getBrandId());
                seriesPo.setRecordVersion(seriesDTO.getRecordVersion());
                seriesPo.setSeriesCode(seriesDTO.getSeriesCode());
                seriesPo.setSeriesName(seriesDTO.getSeriesName());
                seriesPo.setIsValid(seriesDTO.getIsValid());
                seriesPo.setUpdatedAt(LocalDateTime.now());
                seriesPo.setIsIssue(BasedataDictConstants.IS_NO_SEND);
                int updateSize = seriesMapper.updateById(seriesPo);
                if (updateSize == 0) {
                    throw new ServiceBizException(BasedataCommonConstants.UPDATE_FAILED);
                }
                // 发送车系消息到MQ
                sendSeries(seriesPo, BasedataCommonConstants.BIZ_SERIES_UPDATE);
                // 删除redis缓存
                String messageFormat = MessageFormat.format(BaseDataCommonConstants.SERIAL_CACHE_SERIES_ALL, loginInfoDto.getAppId(), loginInfoDto.getGroupCode());
                redisClient.del(messageFormat);
                String productFormat = MessageFormat.format(BaseDataCommonConstants.PRODUCT_CACHE_DATA, loginInfoDto.getAppId(), BasedataCommonConstants.PRODUCT_REDIS_TYPE, BasedataCommonConstants.PRODUCT_REDIS_LEVEL);
                redisClient.del(productFormat);
                return updateSize;
            }
        } else {
            throw new ServiceBizException("后台不存在该车系！");
        }
    }

    /**
     * 车系导出
     *
     * @param queryParam
     * @param request
     * @param response
     * @return void
     * @author renwd
     * @since 2019/7/15
     */
    @Override
    public void exportExcelForSeries(Map<String, Object> queryParam, HttpServletRequest request, HttpServletResponse response) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        MapUtils.addParameter(queryParam, loginInfoDto.getOwnerCode(), loginInfoDto.getAppId(), loginInfoDto.getGroupCode());
        List<Long> brandIdList = dealerBrandService.queryBrandIdList();
        queryParam.put(BasedataCommonConstants.DEALER_BRNAND_LIST, brandIdList);
        List<Map> resultList = seriesMapper.exportExcelForSeries(queryParam);
        Map<String, List<Map>> excelData = new HashMap<>();
        excelData.put("车系信息", resultList);
        List<ExcelExportColumn> exportColumnList = new ArrayList<>();
        exportColumnList.add(new ExcelExportColumn("BRAND_NAME", "品牌名称"));
        exportColumnList.add(new ExcelExportColumn("SERIES_CODE", "车系代码"));
        exportColumnList.add(new ExcelExportColumn("SERIES_NAME", "车系名称"));
//        exportColumnList.add(new ExcelExportColumn("DATA_SOURCES", "数据来源", ExcelDataType.Dict));
        exportColumnList.add(new ExcelExportColumn("IS_VALID", "是否有效", ExcelDataType.Dict));
        excelService.generateExcel(excelData, exportColumnList, "车系信息.xls", request, response);
    }

    /**
     * 车系下拉框
     *
     * @param queryParam
     * @return java.util.List<com.yonyou.cyxdms.basedata.service.vo.series.SeriesDictVO>
     * @author renwd
     * @since 2019/7/16
     */
    @Override
    public List<SeriesDictVO> querySeriesDict(Map<String, Object> queryParam) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        MapUtils.addParameter(queryParam, loginInfo.getOwnerCode(), loginInfo.getAppId(), loginInfo.getGroupCode());
        queryParam.put(BasedataCommonConstants.ORG_TYPE, loginInfo.getOrgType());
        queryParam.put("isValid", BaseDataDictConstants.IS_VALID);
        return seriesMapper.querySeriesDict(queryParam);
    }

    /**
     * 品系型厂端新增编辑车系下拉框（厂端有效）
     *
     * @param queryParam
     * @return java.util.List<com.yonyou.cyxdms.basedata.service.vo.series.SeriesDictVO>
     * @author renwd
     * @since 2019/7/19
     */
    @Override
    public List<SeriesDictVO> queryDcsSeriesDict(Map<String, Object> queryParam) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        MapUtils.addParameter(queryParam, loginInfo.getOwnerCode(), loginInfo.getAppId(), loginInfo.getGroupCode());
        queryParam.put(BasedataCommonConstants.ORG_TYPE, loginInfo.getOrgType());
        queryParam.put(BasedataCommonConstants.DATA_SOURCES, BasedataDictConstants.DATA_SOURCES_BY_SUPER);
        return seriesMapper.querySeriesDict(queryParam);
    }

    /**
     * 车系导入
     *
     * @param importFile
     * @return java.util.List<com.yonyou.cyxdms.basedata.service.dto.vehiclemodel.SeriesImportDTO>
     * @author renwd
     * @since 2019/7/22
     */
    @Override
    public List<SeriesImportDTO> importSeries(MultipartFile importFile) {
        ImportResultDto<SeriesImportDTO> importResult = null;
        try {
            importResult = excelSeriesService.analyzeExcelFirstSheet(importFile,
                    new AbstractExcelReadCallBack<>(SeriesImportDTO.class, this::addSeriesImport));
            return importResult.getDataList();
        } catch (IOException e) {
            logger.error("import error:{}", e);
        }
        return Collections.emptyList();
    }

    /**
     * 是否存在车系
     *
     * @param seriesName
     * @return com.yonyou.cyxdms.basedata.service.entity.series.SeriesPO
     * @author renwd
     * @since 2019/7/22
     */
    @Override
    public SeriesPO existsSeries(String seriesName) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        QueryWrapper<SeriesPO> seriesPoQueryWrapper = new QueryWrapper<>();
        seriesPoQueryWrapper.lambda().eq(SeriesPO::getSeriesName, seriesName)
                .eq(SeriesPO::getAppId, loginInfoDto.getAppId())
                .in(SeriesPO::getOwnerCode, loginInfoDto.getOwnerCode(), loginInfoDto.getGroupCode(), "-1");
        SeriesPO seriesPo = seriesMapper.selectOne(seriesPoQueryWrapper);
        if (StringUtils.isNullOrEmpty(seriesPo)) {
            throw new ServiceBizException("车系名称不存在");
        }
        return seriesPo;
    }

    /**
     * 导入车系
     *
     * @param rowDto
     * @return void
     * @author renwd
     * @since 2019/7/22
     */
    private void addSeriesImport(SeriesImportDTO rowDto, boolean isValidateSucess) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        QueryWrapper<SeriesPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SeriesPO::getSeriesCode, rowDto.getSeriesCode())
                .eq(SeriesPO::getAppId, loginInfoDto.getAppId())
                .in(SeriesPO::getOwnerCode, loginInfoDto.getOwnerCode(), loginInfoDto.getGroupCode(), "-1");
        List<SeriesPO> list = seriesMapper.selectList(queryWrapper);
        if (!CommonUtils.isNullOrEmpty(list)) {
            throw new ServiceBizException(BasedataCommonConstants.SERIES_NOT_REPEAT);
        }

        BrandPO brandPo = brandService.existsBrand(rowDto.getBrandName());

        SeriesPO seriesPo = new SeriesPO();
        seriesPo.setBrandId(brandPo.getBrandId());
        seriesPo.setSeriesCode(rowDto.getSeriesCode());
        seriesPo.setSeriesName(rowDto.getSeriesName());

        String dataSources = rowDto.getDataSources();
        if (StringUtils.isNullOrEmpty(dataSources)) {
            seriesPo.setDataSources(null);
        } else if ("店面".equals(dataSources)) {
            seriesPo.setDataSources(10451001);
        } else if ("主机厂".equals(dataSources)) {
            seriesPo.setDataSources(10451002);
        } else if ("集团".equals(dataSources)) {
            seriesPo.setDataSources(10451003);
        } else {
            throw new ServiceBizException("数据来源不存在");
        }

        String isValid = rowDto.getIsValid();
        if (StringUtils.isNullOrEmpty(isValid)) {
            seriesPo.setIsValid(null);
        } else if ("是".equals(isValid)) {
            seriesPo.setIsValid(10041001);
        } else if ("否".equals(isValid)) {
            seriesPo.setIsValid(10041002);
        } else {
            throw new ServiceBizException("是否有效类型不存在");
        }

        if (isValidateSucess) {
            seriesMapper.insert(seriesPo);
            //车系消息发送到售后
            sendSeries(seriesPo, BasedataCommonConstants.BIZ_SERIES_INSERT);
        }
    }

    /**
     * 通过appid和车系名查车系ID
     *
     * @param:
     * @return:
     * @auther: tanjie
     * @since: 2019/9/6
     */
    @Override
    public Long queryCarserialByAppidAndName(String appId, String serialName) {
        LambdaQueryWrapper<SeriesPO> queryWrapper = new QueryWrapper<SeriesPO>().lambda();
        queryWrapper.eq(SeriesPO::getAppId, appId);
        queryWrapper.eq(SeriesPO::getSeriesName, serialName);
        List<SeriesPO> seriesPos = seriesMapper.selectList(queryWrapper);
        return null != seriesPos && seriesPos.size() > 0 ? seriesPos.get(0).getSeriesId() : null;
    }

    /**
     * @Description: 根据seriesCode 获取车型
     * @Param: [brandId, appId, seriesCode]
     * @Return: com.yonyou.cyxdms.basedata.service.vo.series.SeriesDictVO
     * @Author: lijun
     * @Date: 16:04 2019/8/22
     **/
    @Override
    public SeriesDictVO getByCode(String appId, Long brandId, String seriesCode) {
        return seriesMapper.getByCode(appId, brandId, seriesCode);
    }


    /**
     * code与id映射
     *
     * @param:
     * @return:
     * @auther: tanjie
     * @since: 2019/9/10
     */
    @Override
    public Map<Long, String> querySeriesMapping(String appId) {
        Map<Long, String> map = new HashMap<>();
        LambdaQueryWrapper<SeriesPO> query = new QueryWrapper<SeriesPO>().lambda();
        query.eq(SeriesPO::getAppId, appId);
        List<SeriesPO> seriesPos = seriesMapper.selectList(query);
        for (SeriesPO seriesPo : seriesPos) {
            map.put(seriesPo.getSeriesId(), seriesPo.getSeriesCode());
        }
        return map;
    }

    /**
     * 通用-新增车系、
     *
     * @author：chenzb
     * @since：2019-10-12
     */
    @Override
    public void addSeriesGeneral(List<GeneralSeriesDTO> generalSeriesDtos) {
        logger.debug("厂端同步至后台的车系数据:{}", generalSeriesDtos);
        if (CollectionUtils.isNotEmpty(generalSeriesDtos)) {
            for (GeneralSeriesDTO generalSeriesDTO : generalSeriesDtos) {
                QueryWrapper<SeriesPO> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(SeriesPO::getAppId, generalSeriesDTO.getAppId())
                        .eq(SeriesPO::getSourceId, generalSeriesDTO.getSourceId());
                SeriesPO oldSeriesPo = seriesMapper.selectOne(queryWrapper);
                // 获取品牌code对应的品牌id
                QueryWrapper<BrandPO> brandWrapper = new QueryWrapper<>();
                brandWrapper.lambda().eq(BrandPO::getAppId, generalSeriesDTO.getAppId())
                        .eq(BrandPO::getBrandCode, generalSeriesDTO.getBrandCode());
                BrandPO brandDictVO = brandService.getOne(brandWrapper);
                String ownerCode = StringUtils.isBlank(generalSeriesDTO.getOwnerCode()) ? "-1" : generalSeriesDTO.getOwnerCode();
                // ownerCode设值-1 标记车厂下发
                if (oldSeriesPo == null) {
                    SeriesPO seriesPo = BeanMapperUtil.copyProperties(generalSeriesDTO, SeriesPO.class);
                    seriesPo.setOwnerCode(ownerCode);
                    seriesPo.setCompanyCode(ownerCode);
                    seriesPo.setOwnerParCode(ownerCode);
                    seriesPo.setBrandId(Long.parseLong(brandDictVO.getBrandId().toString()));
                    seriesPo.setSourceChangedAt(LocalDateTime.now());
                    seriesPo.setCreatedAt(LocalDateTime.now());
                    seriesPo.setIsValid(10041001);
                    logger.debug("开始新增插入车系数据:{}", seriesPo);
                    seriesMapper.insert(seriesPo);
                } else {
                    SeriesPO seriesPo = BeanMapperUtil.copyProperties(generalSeriesDTO, SeriesPO.class);
                    seriesPo.setSeriesId(oldSeriesPo.getSeriesId());
                    seriesPo.setBrandId(Long.parseLong(brandDictVO.getBrandId().toString()));
                    seriesPo.setOwnerCode(ownerCode);
                    seriesPo.setCompanyCode(ownerCode);
                    seriesPo.setOwnerParCode(ownerCode);
                    seriesPo.setUpdatedAt(LocalDateTime.now());
                    seriesPo.setCreatedBy("-1");
                    seriesPo.setIsValid(generalSeriesDTO.getIsValid());
                    seriesPo.setRecordVersion(oldSeriesPo.getRecordVersion());
                    seriesPo.setIsDeleted(generalSeriesDTO.getIsDelete() == null ? 0 : generalSeriesDTO.getIsDelete());
                    logger.debug("开始新增更新车系数据:{}", seriesPo);
                    seriesMapper.updateById(seriesPo);
                }
            }
        } else {
            throw new ServiceBizException("厂端传来的车系数据的缺失");
        }
    }

    /**
     * 通过APPID 获取所有
     *
     * @param:
     * @return:
     * @auther: tanjie
     * @since: 2019/11/4
     */
    @Override
    public List<SeriesCacheVO> getAllSeriesByAppId(String appId) {
        LambdaQueryWrapper<SeriesPO> query = new QueryWrapper<SeriesPO>().lambda().eq(SeriesPO::getAppId
                , appId);
        List<SeriesPO> seriesPos = this.seriesMapper.selectList(query);
        return BeanMapperUtil.copyList(seriesPos, SeriesCacheVO.class);
    }

    /**
     * 主机厂和本店所有车系下拉框
     *
     * @param brandsId
     * @author Tansj
     * @since 2019/11/14
     */
    @Override
    public List<SeriesDictVO> querySeriesDictAll(String brandsId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = new HashMap<>();
        queryParam = brandService.setLoginInfoParam(queryParam, loginInfoDto);
        queryParam.put("code", brandsId);
        return seriesMapper.querySeriesDictAll(queryParam);
    }

    /**
     * 新增编辑界面本店面车系下拉框
     *
     * @author Tansj
     * @since 2019/11/18
     */
    @Override
    public List<SeriesDictVO> querySeriesDictOwner(String brandsId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("code", brandsId);
        queryParam = brandService.setLoginInfoParam(queryParam, loginInfoDto);
        // 在新增编辑界面，车系下拉框为本店面的所有有效车系（不包括无效）
        queryParam.put(BasedataCommonConstants.IS_VALID, BaseDataDictConstants.IS_VALID);
        return seriesMapper.querySeriesDictOwner(queryParam);
    }

    /**
     * 新增编辑界面厂端车系下拉框
     *
     * @author Tansj
     * @since 2019/11/18
     */
    @Override
    public List<SeriesDictVO> queryDcsSeriesDictOwner(String brandsId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("code", brandsId);
        queryParam = brandService.setLoginInfoParam(queryParam, loginInfoDto);
        // 在新增编辑界面，车系下拉框为厂端的所有有效车系
        queryParam.put("isValid", BaseDataDictConstants.IS_VALID);
        return seriesMapper.querySeriesDict(queryParam);
    }

    /**
     * 根据登录信息返回车系数据
     *
     * @param seriesQueryDTO
     * @return java.util.List<com.yonyou.cyxdms.basedata.service.vo.series.VehicleProductSeriesVO>
     * @author caozx
     * @since 2020/12/8
     */
    @Transactional(readOnly = true)
    @Override
    public List<VehicleProductSeriesVO> queryVehicleProductSeries(SeriesQueryDTO seriesQueryDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = seriesQueryDTO.toMaps();
        queryParam = brandService.setLoginInfoParam(queryParam, loginInfoDto);
        logger.info("查询车系IPage的queryParam:---------{}", queryParam);
        return seriesMapper.queryVehicleProductSeriesAll(queryParam);
    }

    @Override
    public List<SeriesDictVO> querySeriesDictAll() {
        return seriesMapper.querySeriesDictAllNoPar();
    }
}
